#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
使用pool() 创建指定个数的进程
"""
from multiprocessing import Pool
import os
import time
import random
import functools


def log_time(text):
    def gentror(func):
        @functools.wraps(func)
        def warp(*agrs, **kw):
            start = time.perf_counter()
            print('Process %s start run at %f' % (text, start))
            f = func(*agrs, **kw)
            print('Process %s end' % text)
            end = time.perf_counter()
            print('Process %s run in %f s' % (text, (end - start)))
            return f

        return warp

    return gentror


def long_time_task(name):
    st = time.perf_counter()
    vlaue = "Process :%s run at %f" % (name, st)
    print("Process :%s run at %f" % (name, st))
    print('Run process %s ==> %s' % (name, os.getpid()))
    # start = time.time()
    time.sleep(random.randint(0, 10))
    # end = time.time()
    ed = time.perf_counter()
    # print('Process:%s run in %0.2f seconds.' % (name, end - start))
    print('Process:%s run in %0.2f seconds.' % (name, ed - st))


def main():
    print('Parent process %s start.' % os.getpid())
    # 创建5个进程

    p = Pool(3)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    # 对Pool对象调用join()方法会等待所有子进程执行完毕，调用join()之前必须先调用close()，调用close()之后就不能继续添加新的Process了。
    p.close()
    p.join()

    print('All subprocesses done.')


if __name__ == "__main__":
    main()
